#include "sd_card.h"
#include "SD_MMC.h"
#include "esp_log.h"

#define TAG "sd"

#define MMC_CLK 12
#define MMC_CMD 11
#define MMC_DAT0 13
#define MMC_DAT3 2

// 定义一个变量来跟踪SD卡的挂载状态
bool sd_mounted = false;



void sd_info()
{
    ESP_LOGI(TAG, "Total SD card size: %lluMB", SD_MMC.cardSize() / (1024 * 1024));
    ESP_LOGI(TAG, "Total file system size: %lluB", SD_MMC.totalBytes());
    ESP_LOGI(TAG, "Used file system size: %lluB", SD_MMC.usedBytes());
}
// 挂载SD卡的函数
bool sd_mount()
{
    pinMode(2, OUTPUT);
    digitalWrite(2, 1);
    SD_MMC.setPins(MMC_CLK, MMC_CMD, MMC_DAT0);

    if (!sd_mounted)
    {
        if (SD_MMC.begin("/sdcard", true))
        {
            ESP_LOGI(TAG,"SD card mounted");
            sd_mounted = true;
            uint8_t cardType = SD_MMC.cardType();
            if (cardType == CARD_NONE)
            {
                ESP_LOGI(TAG,"No SD card connected");
                SD_MMC.end();
                return -2;
            }
            else if (cardType == CARD_MMC)
            {
                ESP_LOGI(TAG,"MMC card mounted");
            }
            else if (cardType == CARD_SD)
            {
                ESP_LOGI(TAG,"SDSC card mounted");
            }
            else if (cardType == CARD_SDHC)
            {
                ESP_LOGI(TAG,"SDHC card mounted");
            }
            else
            {
                ESP_LOGI(TAG,"Unknown SD card type mounted");
            }
            sd_info();
            File file = SD_MMC.open("/test.txt", FILE_WRITE);
            file.write('1');
            file.close();
            return true;
        }
        else
        {
            ESP_LOGI(TAG,"Failed to mount SD card");
            return false;
        }
    }
    return false;
}

// 卸载SD卡的函数
void sd_unmount()
{
    if (sd_mounted)
    {
        SD_MMC.end();
        sd_mounted = false;
    }
    return;
}


void sd_auto_mount(void *pvParamers)
{
    uint8_t buf[10]={'1'};
    int ret;
    while (1)
    {
        if (sd_mounted)
        {
            // 尝试读取一个文件来检查 SD 卡是否仍可访问
            File file = SD_MMC.open("/test.txt", FILE_READ);
            if (file) {
                ret = file.read(buf,1);
                if(ret != 1)
                {
                    ESP_LOGI(TAG,"sd_unmount");
                    sd_unmount(); 
                }
            } else {
                ESP_LOGI(TAG,"Failed open");
                sd_unmount();
            }
            file.close();

        }
        else
        {
            sd_mount();

        }
        delay(1000);
    }
}
void sdcard_init()
{

    xTaskCreate(
        sd_auto_mount,   // 任务函数
        "sd_auto_mount", // 任务名称
        10000,           // 任务堆栈大小
        NULL,            // 传递给任务函数的参数
        5,               // 任务优先级
        NULL             // 任务句柄
    );
}